<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item
        style="display: none;"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['id']"/>
      </a-form-item>

      <a-form-item
        label="角色名"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        has-feedback
      >
        <a-input placeholder="请输入角色名" v-decorator="['name', {rules: [{required: true, message: '请输入角色名！'}]}]"/>
      </a-form-item>
      <a-form-item
        label="描述信息"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-textarea placeholder="请输入描述信息" :rows="3"
                    v-decorator="['desc', {rules: [{required: false, message: '请输入描述信息！'}]}]"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
  import * as api from '@/api/system/roleManage'
  // 导入提示信息字典
  import config from '@/config/dict'

  export default {
    name: 'sForm',
    data() {
      return {
        labelCol: {
          xs: { span: 10 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        title: '',
        form: this.$form.createForm(this)
      }
    },
    methods: {
      // 初始化方法
      open(record) {
        if (record) {
          this.title = '编辑角色'
          setTimeout(() => {
            this.setUserItem(record)
          }, 100)
        } else {
          this.title = '新增角色'
        }
        this.visible = true
      },
      setUserItem(record) {
        this.form.setFieldsValue(
          {
            id: record.id,
            name: record.name,
            desc: record.desc
          }
        )
      },
      // [确认按钮]提交数据方法
      handleSubmit() {
        const { form: { validateFields } } = this
        validateFields((errors, values) => {
            if (!errors) {
              if (values.id) {
                this.message = config.msgDict[1]
                api.updateObj(values)
                  .then((res) => {
                    this._handle_response(res, values)
                  })
              } else {
                this.message = config.msgDict[0]
                api.addObj(values)
                  .then((res) => {
                    this._handle_response(res, values)
                  })
              }
            }
          }
        )
      },
      // 处理返回消息
      _handle_response(res, values) {
        if (res.success) {
          this.$message.success(this.message['success'])
          this.handleCancel()
          this.$emit('ok', values)
        } else {
          this.$message.error(this.message['failed'] + res.error)
        }
      }
      ,
      // [取消按钮]重置数据,关闭弹框
      handleCancel() {
        this.form.resetFields()
        this.visible = false
      }
    }
  }
</script>
